/**
 * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.demo.api;

import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.kit.ParaMap;

/**
 * 认证并获取 token API
 * http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token
 */
public class JsTokenApis {
	
	// "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	private static String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";
	
	private static JsToken accessToken;
	
	public static JsToken getAccessToken() {
		if (accessToken != null && accessToken.isAvailable())
			return accessToken;
		
		refreshAccessToken();
		return accessToken;
	}
	
	public static void refreshAccessToken() {
		accessToken = requestAccessToken();
	}
	
	private static synchronized JsToken requestAccessToken() {
		JsToken result = null;
		String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
		System.out.println("==================="+accessToken);
		for (int i=0; i<3; i++) {
			Map<String, String> queryParas = ParaMap.create("access_token", accessToken).getData();
			String json = HttpKit.get(url, queryParas);
			result = new JsToken(json);
			
			if (result.isAvailable())
				break;
		}
		return result;
	}
	
	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
	
		
		JsToken at = getAccessToken();
		if (at.isAvailable())
			System.out.println("access_token : " + at.getAccessToken());
		else
			System.out.println(at.getErrorCode() + " : " + at.getErrorMsg());
	}
}
